<template>
  <!-- 弹框 -->
  <el-dialog v-model="showDialog" v-bind="mergedDialogConfig">
    <!-- 全局表单组件 -->
    <UiForm v-model:formData="formData" v-bind="formConfig" @handleFormItemChange="handleFormItemChange"
      ref="uiFormRef">
      <!-- 插槽嵌套  UiForm 自定义插槽 custom-slot-->
      <template #custom-slot>
        <!-- UiModalForm 默认插槽 -->
        <slot></slot>
      </template>
    </UiForm>
  </el-dialog>
</template>

<script setup lang="js">
import { ref, computed } from "vue"

const emits = defineEmits(["update:modelValue", "callHandleFormItemChange"])

const props = defineProps({
  // 组件双向数据绑定
  modelValue: {
    type: Object,
    require: true
  },
  // 表单配置
  formConfig: {
    type: Object,
    require: true
  },
  // 弹框配置
  dialogConfig: {
    type: Object,
    require: false
  }
})

// 用 computed 做双向绑定：读 props，写时 emit 回父组件
const formData = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  }
})

// uiForm dom
const uiFormRef = ref()

// 弹框是否显示
const showDialog = ref(false)

// 解决 v-bind 不能初始化值dialogConfig
const mergedDialogConfig = computed(() => ({
  title: "",
  ...props.dialogConfig
}));

// 表单循环每一选项 change事件
const handleFormItemChange = (value, item) => {
  // 处理表单选项 定制开发
  emits("callHandleFormItemChange", value, item)
}

// 校验弹框表单Form
const validateModalForm = (callBack) => {
  uiFormRef.value?.validateForm((valid) => {
    if (valid) {
      callBack(valid)
    }
  });
}

// 打开弹框
const open = () => {
  showDialog.value = true
}

// 关闭弹框
const close = () => {
  showDialog.value = false
}

// 修改弹框标题
const updateDialogTitle = (title) => {
  mergedDialogConfig.value.title = title
}

defineExpose({ open, close, updateDialogTitle, validateModalForm })
</script>
<style scoped lang="scss"></style>